<template>
  <div v-loading="loading">
    <input
      type="text"
      class="address"
      v-model="iMap.address"
      id="inputAddress"
    />
    <div id="container"></div>
  </div>
</template>

<script setup lang="ts" name="AmapContainer">
import { ref, reactive, watch, onMounted, onUnmounted } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { AMAP_MAP_KEY, AMAP_SECRET_KEY } from '@/config'
import type { IMap } from '../interface/index'

const loading = ref(true)

interface ExtendsWindow extends Window {
  _AMapSecurityConfig?: {
    securityJsCode: string
  }
}
let _window: ExtendsWindow = window

// 定义map实例
let map: any = null

const iMap = reactive<IMap>({
  province: '',
  city: '',
  district: '',
  address: '',
  lnglat: [114.525918, 38.032612],
  canSubmit: true,
})

watch(
  () => iMap.address,
  () => {
    iMap.canSubmit = !iMap.address
  },
)

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  map?.destroy()
})

// 初始化地图
const initMap = async () => {
  _window._AMapSecurityConfig = {
    securityJsCode: AMAP_SECRET_KEY,
  }
  AMapLoader.load({
    key: AMAP_MAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      'AMap.ToolBar',
      'AMap.Scale',
      'AMap.Marker',
      'AMap.Geocoder',
      'AMap.AutoComplete',
    ], //需要使用的的插件列表
  })
    .then(AMap => {
      map = new AMap.Map('container', {
        // 设置地图容器id
        viewMode: '2D', // 是否为3D地图模式
        zoom: 11, // 初始化地图级别
        center: iMap.lnglat, // 初始化地图中心点位置
      })
      //创建工具条插件实例
      const toolbar = new AMap.ToolBar({
        position: {
          top: '110px',
          right: '40px',
        },
      })
      map.addControl(toolbar)

      //创建比例尺插件实例
      const Scale = new AMap.Scale()
      map.addControl(Scale)

      //创建标记插件实例
      const Marker = new AMap.Marker({
        position: iMap.lnglat,
      })
      map.addControl(Marker)

      //创建地理编码插件实例
      const Geocoder: any = new AMap.Geocoder({
        radius: 1000, //以已知坐标为中心点，radius为半径，返回范围内兴趣点和道路信息
        extensions: 'base', //返回地址描述以及附近兴趣点和道路信息，默认“base | all”
      })

      //返回地理编码结果
      Geocoder.getAddress(iMap.lnglat, (status:any, result:any) => {
        if (status === 'complete' && result.info === 'OK') {
          iMap.province = result.regeocode.addressComponent.province
          iMap.city = result.regeocode.addressComponent.city
          iMap.district = result.regeocode.addressComponent.district
          iMap.address = result.regeocode.formattedAddress
          AutoComplete.setCity(iMap.address)
          loading.value = false
        }
      })
      // 根据输入关键字提示匹配信息
      const AutoComplete = new AMap.AutoComplete({
        input: 'inputAddress',
        city: iMap.address,
        datatype: 'all',
      })

      AutoComplete.on('select', (result:any) => {
        iMap.lnglat = [result.poi.location.lng, result.poi.location.lat]
        setPointOrAddress()
      })

      //点击地图事件
      map.on('click', (e:any) => {
        iMap.lnglat = [e.lnglat.lng, e.lnglat.lat]
        setPointOrAddress()
      })

      // 设置地图点坐标与位置交互
      const setPointOrAddress = () => {
        Marker.setPosition(iMap.lnglat)
        map.setCenter(iMap.lnglat)
        map.setZoom(12)
        Geocoder.getAddress(iMap.lnglat, (status:any, result:any) => {
          if (status === 'complete' && result.info === 'OK') {
            iMap.province = result.regeocode.addressComponent.province
            iMap.city = result.regeocode.addressComponent.city
            iMap.district = result.regeocode.addressComponent.district
            iMap.address = result.regeocode.formattedAddress
          }
        })
      }
    })
    .catch(e => {
      console.log(e)
    })
}

defineExpose({
  iMap,
})
</script>

<style scoped lang="scss">
@import '../index.scss';
</style>

<style lang="scss">
.amap-sug-result {
  z-index: 10000;
}
</style>
